package com.wy2cloud.authorize.handler;

import java.io.IOException;
import java.security.Principal;
import java.util.Collection;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.security.web.util.UrlUtils;
import org.springframework.util.StringUtils;

import com.wy2cloud.authorize.security.LoginUrlAuthenticationEntryPointAdapter;
import com.wy2cloud.authorize.util.ProxyPrefixHttpServletRequestWrapper;


//可以在这里将用户登录信息存入数据库。
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler{  
    
    private Logger logger=LoggerFactory.getLogger(LoginSuccessHandler.class);
    
    private RequestCache requestCache = new HttpSessionRequestCache();
    
    @Override  
    public void onAuthenticationSuccess(HttpServletRequest request,  
            HttpServletResponse response, Authentication authentication) throws IOException,  
            ServletException {  
        if(authentication instanceof UsernamePasswordAuthenticationToken) {
           UserDetails user= (UserDetails) authentication.getPrincipal();
           Collection<? extends GrantedAuthority> authoritites = user.getAuthorities();
           
           logger.info("{} 登录成功",user.getUsername());
           for (GrantedAuthority grantedAuthority : authoritites) {
               logger.info("拥有权限:{}",grantedAuthority.getAuthority());
           }

               
        }

        request = new ProxyPrefixHttpServletRequestWrapper(request,true);
        logger.info("LoginSuccess contextPath: {}",request.getContextPath());
              
        DefaultSavedRequest savedRequest = (DefaultSavedRequest) requestCache.getRequest(request, response);

		if (savedRequest == null) {
			super.onAuthenticationSuccess(request, response, authentication);

			return;
		}
		String targetUrlParameter = getTargetUrlParameter();
		if (isAlwaysUseDefaultTargetUrl()
				|| (targetUrlParameter != null && StringUtils.hasText(request
						.getParameter(targetUrlParameter)))) {
			requestCache.removeRequest(request, response);
			super.onAuthenticationSuccess(request, response, authentication);

			return;
		}

		clearAuthenticationAttributes(request);

		// Use the DefaultSavedRequest URL
//		String targetUrl =UrlUtils.buildFullRequestUrl(savedRequest.getScheme(),
//				savedRequest.getServerName(), 
//				savedRequest.getServerPort(), request.getContextPath()+savedRequest.getRequestURI(),
//				savedRequest.getQueryString());
		String targetUrl =savedRequest.getRedirectUrl();
		
		
        
		logger.info("Redirecting to DefaultSavedRequest Url: " + targetUrl);
		getRedirectStrategy().sendRedirect(request, response, targetUrl);  
    }  
    
    public String getIpAddress(HttpServletRequest request){    
        String ip = request.getHeader("x-forwarded-for");    
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("Proxy-Client-IP");    
        }    
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("WL-Proxy-Client-IP");    
        }    
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("HTTP_CLIENT_IP");    
        }    
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");    
        }    
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
            ip = request.getRemoteAddr();    
        }    
        return ip;    
    }  
      
}
